oauth2 {nest.js} {passport}
- 0018.1 Nest.js ๐ฑ
- dev.to ๋ธ๋ก๊ทธ๊ธ
- oauth {django}
- google oauth ๋ฌธ์
- @nestjs/passport ๋ฌธ์ passport ํจํค์ง ๋ํผ์ธ @nestjs/passport์ ๋ํด์ ์์๋ณธ๋ค.
overview
strategy ์์ฑํ๊ณ ๋ชจ๋๊ณผ ์๋น์ค ์์ฑํ๊ณ , ์ง์ ์ ์ผ๋ก strategy ์ฝ๋๋ฅผ ํธ์ถํ์ง๋ ์๊ณ AuthModule
์ด๋ผ๋ ๊ฐ๋๋ฅผ ์ด๋
ธํ
์ด์
์ผ๋ก ๋ถ์ฌ๋๋๊ฑธ๋ก ๊ตฌํ ๊ฐ๋ฅ. controller์์ ์ธ๊ฐ๊ฐ ํ์ํ ์๋ํฌ์ธํธ์ ๊ฐ๋๋ฅผ ๊ฑธ์ด๋๋๋ค. ์ค์ authenticate ๋จ๊ณ๋ฅผ ์ํด์ built-in passport guards๋ฅผ ์ฌ์ฉํจ.
- strategy๊ฐ ํ๋ ์ผ
- retrieving credentials
- running verify function
- creating
user
property
// src/auth/kakao.strategy.ts
export class KakaoStrategy extends PassportStrategy(Strategy, 'kakao') {
constructor() {
super({
clientID: process.env.KAKAO_CLIENT_ID,
clientSecret: process.env.KAKAO_CLIENT_SECRET,
callbackURL: 'http://chltm.mooo.com:3000/auth/kakao',
});
}
async validate(
accessToken: string,
refreshToken: string,
profile: any,
done: any,
) {
const { id, username, email, provider } = profile;
console.log(profile);
const user = {
id,
username,
provider,
email,
accessToken,
refreshToken,
};
done(null, user);
}
}
- controller๊ฐ ํ๋ ์ผ
AuthGard
๋ฅผ ๋ฑ๋กํ์ฌ ์ฌ์ฉ์ ์ธ๊ฐ์์ ์ ๋ํ ์ฑ ์์ ํํผ- ์ฃผ์ ๋ฐ์ service ๋ฉ์๋๋ฅผ ํธ์ถํ์ฌ ์ํ๋ ์์ ์ ๋์ ํจ.
- ๊ฒฐ๊ตญ ์๋ ์ฑ ์์ ๊ฐ๋ง ์ด์ฌํ ํ๋ ๋ ์์
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('kakao')
@UseGuards(AuthGuard('kakao'))
async kakaoAuth(@Req() req): Promise<any> {
return this.authService.kakaoLogin(req);
}
}
- service๊ฐ ํ๋ ์ผ
AuthGuard
๊ฐ authorization server์ ์์ฒญ์ ๋ ๋ ค ์ป์ ์ ์ ์ ๋ณด๋ฅผreq.user
์ ๋ฃ์์ ๊ฒ์.
Strategy
- ์ธ์ฆ ๋จ๊ณ๋ฅผ JWT, OAuth, username/password strategy๋ก ์ ํํ ์ ์์.
- ๊ฒ์ฆ๋จ๊ณ๋ verify callback์ ์ฌ์ฉํ๊ฒ ๋๋ค.
Kakao Oauth2
https://www.passportjs.org/packages/passport-kakao/
npm i passport-kakao
์ ์ ํ๋ฆฌ์ผ์ด์ ์ ๋ฑ๋ก โถ ์นด์นด์ค ๋ก๊ทธ์ธ ํญ์์ ํ์ฑํ + OpenID Connect + Redirect URI ์ค์ โถ ํ๋ซํผ ํญ์์ Web ์ฌ์ดํธ ๋๋ฉ์ธ ์ถ๊ฐ โถ ์ฑ ํค ํญ์์ ๊ฐ๊ฐ REST API ํค์ Admin ํค๋ฅผ Client ID & Secrete Key์ ๋์ํ์ฌ ์ ์
email์ด ํ์๋์๊ฐ ์๋ ๊ฒ์ด๋ค. ์ด ๊ฒฝ์ฐ, ๋น์ฆ๋์ค ํญ์ผ๋ก ๊ฐ์ ๊ฐ์ธ ๊ฐ๋ฐ์ ๋น์ฆ ์ฑ์ ๋ฑ๋กํ๋ฉด ๋๋ค.